package com.novel.common.utils;

import com.novel.common.utils.model.IpInfo;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Ip2Region 本地获取ip地址工具
 *
 * @author novel
 * @since 2020/3/24
 */
@Slf4j
public class Ip2RegionUtil {
    private static final String PATH = "/ip2region.xdb";
    private static byte[] data;

    static {
        try {
            InputStream inputStream = new ClassPathResource(PATH).getInputStream();
            data = FileCopyUtils.copyToByteArray(inputStream);
        } catch (Exception e) {
            log.error("Ip2RegionUtil init error:{}", e.getMessage());
            try {
                String filePath = ResourceUtils.getURL("classpath:").getPath() + PATH;
                filePath = filePath.substring(1);
                Path path = Paths.get(filePath);
                data = Files.readAllBytes(path);
            } catch (Exception e1) {
                log.error("Ip2RegionUtil init error:{}", e1.getMessage());
            }
        }
    }


    /**
     * 获取ip地址
     *
     * @param ip ipv4
     * @return 地址信息
     */
    public static IpInfo find(String ip) {
        try {
            Searcher searcher = Searcher.newWithBuffer(data);
            //采用Btree搜索
            String block = searcher.search(ip);
            //打印位置信息（格式：国家|大区|省份|城市|运营商）
            String[] split = block.split("\\|");
            IpInfo info = new IpInfo();

            info.setCountry(split[0]);
            info.setArea(split[1]);
            info.setProvince(split[2]);
            info.setCity(split[3]);
            info.setIsp(split[4]);

            return info;
        } catch (Exception e) {
           log.error("Ip2RegionUtil find error:{}", e.getMessage());
        }
        return null;
    }
}
